package com.headStorm.concurrent.manyThread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolStopThread {
    static class MyRunnable implements Runnable {

        private String jobName;
        private Thread nowThread;

        MyRunnable(String jobName) {
            this.jobName = jobName;
        }

        public void setInterrupted() {
            nowThread.interrupt();
        }

        @Override
        public void run() {
            nowThread = Thread.currentThread();
            try {
                while (true) {
                    Thread.sleep(1000);
                    // 写了sleep就不用再判断isInterrupted()了
                    System.err.println("当前线程：" + Thread.currentThread().getName() + " 当前任务：" + jobName);
                }
            } catch (InterruptedException e) {
                System.err.println("当前线程：" + Thread.currentThread().getName() + " 当前任务：" + jobName + "马上停止");
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
       // ExecutorService es = Executors.newFixedThreadPool(2);
        ExecutorService es = Executors.newCachedThreadPool();
        MyRunnable job1 = new MyRunnable("job-1");
        MyRunnable job2 = new MyRunnable("job-2");
        MyRunnable job3 = new MyRunnable("job-3");
        es.execute(job1);
        es.execute(job2);
        es.execute(job3);
//        System.err.println("5s后停止job-1");
//        Thread.sleep(5000);
//        job1.setInterrupted();
    }
}
